import React, { useState, useEffect } from 'react';
import { createDomainWithWizard, checkDomainName, getHostResources, listStoragePools, listNetworks } from '../api/client';
import './CreateVMWizardPodman.css';

interface CreateVMWizardPodmanProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: (vm: any) => void;
}

// 创建方法枚举
type CreateMethod = 'local_iso' | 'network' | 'import_disk' | 'manual';

interface VMFormData {
  // 创建方法选择
  method: CreateMethod;

  // 基本信息
  name: string;
  description: string;
  osType: string;
  osVersion: string;

  // 资源配置
  vcpus: number;
  memory: number;
  memoryUnit: 'MB' | 'GB';
  cpuModel: string;

  // 存储配置
  storagePool: string;
  diskSize: number;
  diskFormat: string;
  diskBus: string;
  cacheMode: string;

  // 网络配置
  networkType: string;
  networkName: string;
  networkModel: string;
  macAddress: string;

  // 启动选项
  bootOrder: string[];
  autostart: boolean;
  bootDelay: number;
  loader: string;
  graphics: string;
  displayProtocol: string;

  // 本地ISO配置
  localIsoPath: string;
  localIsoCdrom: boolean;

  // 网络安装配置
  networkSource: string;
  networkKernel: string;
  networkInitrd: string;
  networkExtra: string;

  // 磁盘导入配置
  importDiskPath: string;
  importCopy: boolean;

  // 手动创建配置
  customXml: string;
}

const CreateVMWizardPodman: React.FC<CreateVMWizardPodmanProps> = ({ isOpen, onClose, onSuccess }) => {
  const [currentStep, setCurrentStep] = useState(1);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [hostResources, setHostResources] = useState<any>(null);
  const [storagePools, setStoragePools] = useState<any[]>([]);
  const [networks, setNetworks] = useState<any[]>([]);
  const [nameAvailable, setNameAvailable] = useState<boolean | null>(null);
  const [isCheckingName, setIsCheckingName] = useState(false);
  const [autoSaveStatus, setAutoSaveStatus] = useState<'idle' | 'saving' | 'saved'>('idle');

  // 从 localStorage 加载保存的表单数据
  const loadSavedFormData = (): VMFormData => {
    try {
      const saved = localStorage.getItem('vm-wizard-form-data');
      if (saved) {
        const parsed = JSON.parse(saved);
        // 合并默认数据和保存的数据
        return {
          ...getDefaultFormData(),
          ...parsed,
          // 重置一些不应该保存的字段
          name: '',
          description: '',
          localIsoPath: '',
          networkSource: '',
          importDiskPath: '',
          customXml: ''
        };
      }
    } catch (error) {
      console.warn('Failed to load saved form data:', error);
    }
    return getDefaultFormData();
  };

  // 获取默认表单数据
  const getDefaultFormData = (): VMFormData => ({
    method: 'local_iso',
    name: '',
    description: '',
    osType: 'linux',
    osVersion: 'ubuntu22.04',
    vcpus: 2,
    memory: 2,
    memoryUnit: 'GB',
    cpuModel: 'host-model',
    storagePool: 'default',
    diskSize: 20,
    diskFormat: 'qcow2',
    diskBus: 'virtio',
    cacheMode: 'writeback',
    networkType: 'nat',
    networkName: 'default',
    networkModel: 'virtio',
    macAddress: '',
    bootOrder: ['cdrom', 'hd'],
    autostart: false,
    bootDelay: 0,
    loader: 'uefi',
    graphics: 'vnc',
    displayProtocol: 'vnc',
    localIsoPath: '',
    localIsoCdrom: true,
    networkSource: '',
    networkKernel: '',
    networkInitrd: '',
    networkExtra: '',
    importDiskPath: '',
    importCopy: false,
    customXml: ''
  });

  const [formData, setFormData] = useState<VMFormData>(loadSavedFormData());

  // 根据创建方法确定步骤
  const getWizardSteps = () => {
    const baseSteps = [
      { id: 1, title: '选择方法', component: 'MethodSelection' },
      { id: 2, title: '基本信息', component: 'BasicInfo' },
      { id: 3, title: '资源配置', component: 'Resources' }
    ];

    switch (formData.method) {
      case 'local_iso':
        return [
          ...baseSteps,
          { id: 4, title: 'ISO配置', component: 'ISOConfig' },
          { id: 5, title: '存储配置', component: 'StorageConfig' },
          { id: 6, title: '网络配置', component: 'NetworkConfig' },
          { id: 7, title: '启动选项', component: 'BootOptions' }
        ];
      case 'network':
        return [
          ...baseSteps,
          { id: 4, title: '网络安装', component: 'NetworkInstall' },
          { id: 5, title: '存储配置', component: 'StorageConfig' },
          { id: 6, title: '网络配置', component: 'NetworkConfig' },
          { id: 7, title: '启动选项', component: 'BootOptions' }
        ];
      case 'import_disk':
        return [
          ...baseSteps,
          { id: 4, title: '磁盘导入', component: 'DiskImport' },
          { id: 5, title: '网络配置', component: 'NetworkConfig' },
          { id: 6, title: '启动选项', component: 'BootOptions' }
        ];
      case 'manual':
        return [
          ...baseSteps,
          { id: 4, title: 'XML配置', component: 'XMLConfig' }
        ];
      default:
        return baseSteps;
    }
  };

  const steps = getWizardSteps();

  // 加载初始化数据
  useEffect(() => {
    if (isOpen) {
      loadInitialData();
      generateMACAddress();
    }
  }, [isOpen]);

  // 键盘导航支持
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (!isOpen) return;

      switch (e.key) {
        case 'Escape':
          if (!isSubmitting) {
            onClose();
          }
          break;
        case 'Enter':
          if (e.ctrlKey || e.metaKey) {
            e.preventDefault();
            if (currentStep === steps.length) {
              handleSubmit();
            } else {
              handleNext();
            }
          }
          break;
        case 'ArrowLeft':
          if (e.ctrlKey || e.metaKey) {
            e.preventDefault();
            handlePrevious();
          }
          break;
        case 'ArrowRight':
          if (e.ctrlKey || e.metaKey) {
            e.preventDefault();
            if (currentStep < steps.length) {
              handleNext();
            }
          }
          break;
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [isOpen, currentStep, steps.length, isSubmitting]);

  // 检查名称可用性
  useEffect(() => {
    if (formData.name.trim()) {
      checkNameAvailability(formData.name.trim());
    } else {
      setNameAvailable(null);
    }
  }, [formData.name]);

  // 自动保存表单数据（排除敏感字段）
  useEffect(() => {
    if (!isOpen) return;

    const timer = setTimeout(() => {
      setAutoSaveStatus('saving');
      try {
        const dataToSave = {
          method: formData.method,
          osType: formData.osType,
          osVersion: formData.osVersion,
          vcpus: formData.vcpus,
          memory: formData.memory,
          memoryUnit: formData.memoryUnit,
          cpuModel: formData.cpuModel,
          storagePool: formData.storagePool,
          diskSize: formData.diskSize,
          diskFormat: formData.diskFormat,
          diskBus: formData.diskBus,
          cacheMode: formData.cacheMode,
          networkType: formData.networkType,
          networkName: formData.networkName,
          networkModel: formData.networkModel,
          bootOrder: formData.bootOrder,
          autostart: formData.autostart,
          bootDelay: formData.bootDelay,
          loader: formData.loader,
          graphics: formData.graphics,
          displayProtocol: formData.displayProtocol,
          localIsoCdrom: formData.localIsoCdrom,
          importCopy: formData.importCopy
        };
        localStorage.setItem('vm-wizard-form-data', JSON.stringify(dataToSave));
        setAutoSaveStatus('saved');
        setTimeout(() => setAutoSaveStatus('idle'), 2000);
      } catch (error) {
        console.warn('Failed to auto-save form data:', error);
        setAutoSaveStatus('idle');
      }
    }, 1000);

    return () => clearTimeout(timer);
  }, [formData, isOpen]);

  const loadInitialData = async () => {
    try {
      const [resourcesRes, poolsRes, networksRes] = await Promise.all([
        getHostResources(),
        listStoragePools(),
        listNetworks()
      ]);

      setHostResources(resourcesRes.data);
      setStoragePools(poolsRes.data.pools || []);
      setNetworks(networksRes.data.networks || []);
    } catch (error) {
      console.error('Failed to load initial data:', error);
    }
  };

  const generateMACAddress = () => {
    const mac = '52:54:00' + Array.from({length: 3}, () =>
      Math.floor(Math.random() * 256).toString(16).padStart(2, '0')
    ).join(':');
    setFormData(prev => ({ ...prev, macAddress: mac }));
  };

  const checkNameAvailability = async (name: string) => {
    setIsCheckingName(true);
    try {
      const response = await checkDomainName(name);
      setNameAvailable(response.data.available);
    } catch (error) {
      setNameAvailable(false);
    } finally {
      setIsCheckingName(false);
    }
  };

  const handleNext = () => {
    if (validateCurrentStep()) {
      if (currentStep < steps.length) {
        setCurrentStep(currentStep + 1);
      } else {
        handleSubmit();
      }
    }
  };

  const handlePrevious = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
    }
  };

  const validateCurrentStep = (): boolean => {
    const newErrors: Record<string, string> = {};
    const currentStepData = steps[currentStep - 1];

    switch (currentStepData.component) {
      case 'MethodSelection':
        if (!formData.method) {
          newErrors.method = '请选择创建方法';
        }
        break;

      case 'BasicInfo':
        if (!formData.name.trim()) {
          newErrors.name = '虚拟机名称不能为空';
        } else if (!/^[a-zA-Z0-9_-]+$/.test(formData.name)) {
          newErrors.name = '名称只能包含字母、数字、下划线和连字符';
        } else if (nameAvailable === false) {
          newErrors.name = '该名称已被使用';
        }
        if (!formData.osType) {
          newErrors.osType = '请选择操作系统类型';
        }
        break;

      case 'Resources':
        if (formData.vcpus < 1 || formData.vcpus > 128) {
          newErrors.vcpus = 'CPU核心数必须在1-128之间';
        }
        if (formData.memory < 1) {
          newErrors.memory = '内存不能小于1GB';
        }
        if (hostResources && formData.memory > (hostResources.memory.total / 1024 / 1024 / 1024) * 0.8) {
          newErrors.memory = '内存不能超过宿主机总内存的80%';
        }
        break;

      case 'ISOConfig':
        if (!formData.localIsoPath.trim()) {
          newErrors.localIsoPath = '请选择ISO文件路径';
        }
        break;

      case 'NetworkInstall':
        if (!formData.networkSource.trim()) {
          newErrors.networkSource = '请填写网络安装源URL';
        }
        break;

      case 'DiskImport':
        if (!formData.importDiskPath.trim()) {
          newErrors.importDiskPath = '请选择要导入的磁盘映像路径';
        }
        break;

      case 'XMLConfig':
        if (!formData.customXml.trim()) {
          newErrors.customXml = '请输入XML配置';
        }
        break;
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async () => {
    if (!validateCurrentStep()) {
      return;
    }

    setIsSubmitting(true);

    // 清除之前的错误
    setErrors({});

    try {
      // 转换内存为MB
      const memoryMB = formData.memoryUnit === 'GB' ? formData.memory * 1024 : formData.memory;

      // 构建向导规格
      const wizardSpec = {
        method: formData.method,
        name: formData.name,
        description: formData.description,
        osType: formData.osType,
        osVersion: formData.osVersion,
        vcpus: formData.vcpus,
        memory: memoryMB,
        memoryUnit: 'MB',
        cpuModel: formData.cpuModel,
        storagePool: formData.storagePool,
        diskSize: formData.diskSize,
        diskFormat: formData.diskFormat,
        diskBus: formData.diskBus,
        cacheMode: formData.cacheMode,
        networkType: formData.networkType,
        networkName: formData.networkName,
        networkModel: formData.networkModel,
        macAddress: formData.macAddress,
        bootOrder: formData.bootOrder,
        autostart: formData.autostart,
        bootDelay: formData.bootDelay,
        loader: formData.loader,
        graphics: formData.graphics,
        displayProtocol: formData.displayProtocol,
        local_iso_path: formData.localIsoPath,
        local_iso_cdrom: formData.localIsoCdrom,
        network_source: formData.networkSource,
        network_kernel: formData.networkKernel,
        network_initrd: formData.networkInitrd,
        network_extra: formData.networkExtra,
        import_disk_path: formData.importDiskPath,
        import_copy: formData.importCopy,
        custom_xml: formData.customXml
      };

      // 清理之前的表单数据
      localStorage.removeItem('vm-wizard-form-data');

      const response = await createDomainWithWizard(wizardSpec);

      // 显示成功消息
      onSuccess(response.data);

      // 延迟关闭以显示成功状态
      setTimeout(() => {
        onClose();
      }, 500);

    } catch (error: any) {
      console.error('Failed to create VM:', error);

      // 更详细的错误处理
      let errorMessage = '创建虚拟机失败';

      if (error.response?.data?.detail) {
        errorMessage = error.response.data.detail;
      } else if (error.response?.data?.error) {
        errorMessage = error.response.data.error;
      } else if (error.message) {
        errorMessage = error.message;
      }

      // 根据错误类型提供更具体的建议
      if (errorMessage.includes('ISO')) {
        errorMessage += ' - 请检查ISO文件路径是否正确且文件存在';
      } else if (errorMessage.includes('network')) {
        errorMessage += ' - 请检查网络安装源URL是否可访问';
      } else if (errorMessage.includes('disk')) {
        errorMessage += ' - 请检查磁盘映像文件是否存在且格式正确';
      } else if (errorMessage.includes('XML')) {
        errorMessage += ' - 请检查XML配置是否符合libvirt规范';
      }

      setErrors({ submit: errorMessage });

      // 滚动到错误位置
      setTimeout(() => {
        const errorElement = document.querySelector('.wizard-error');
        if (errorElement) {
          errorElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
      }, 100);

    } finally {
      setIsSubmitting(false);
    }
  };

  const renderStepContent = () => {
    const currentStepData = steps[currentStep - 1];

    switch (currentStepData.component) {
      case 'MethodSelection':
        return (
          <div className="step-content method-selection">
            <h2 className="step-title">选择创建方法</h2>
            <p className="step-description">选择最适合您需求的虚拟机创建方式</p>

            <div className="method-cards">
              <div
                className={`method-card ${formData.method === 'local_iso' ? 'selected' : ''}`}
                onClick={() => setFormData({ ...formData, method: 'local_iso' })}
              >
                <div className="method-icon">💿</div>
                <h3>本地ISO安装</h3>
                <p>从本地ISO文件安装操作系统</p>
                <div className="method-features">
                  <span>• CD-ROM设备配置</span>
                  <span>• 启动顺序设置</span>
                </div>
              </div>

              <div
                className={`method-card ${formData.method === 'network' ? 'selected' : ''}`}
                onClick={() => setFormData({ ...formData, method: 'network' })}
              >
                <div className="method-icon">🌐</div>
                <h3>网络安装</h3>
                <p>通过网络安装源创建虚拟机</p>
                <div className="method-features">
                  <span>• HTTP/FTP源</span>
                  <span>• 网络引导配置</span>
                </div>
              </div>

              <div
                className={`method-card ${formData.method === 'import_disk' ? 'selected' : ''}`}
                onClick={() => setFormData({ ...formData, method: 'import_disk' })}
              >
                <div className="method-icon">💾</div>
                <h3>磁盘映像导入</h3>
                <p>从现有磁盘映像导入虚拟机</p>
                <div className="method-features">
                  <span>• 磁盘挂载</span>
                  <span>• 启动参数配置</span>
                </div>
              </div>

              <div
                className={`method-card ${formData.method === 'manual' ? 'selected' : ''}`}
                onClick={() => setFormData({ ...formData, method: 'manual' })}
              >
                <div className="method-icon">⚙️</div>
                <h3>手动创建</h3>
                <p>完全自定义虚拟机配置</p>
                <div className="method-features">
                  <span>• XML自定义</span>
                  <span>• 高级配置</span>
                </div>
              </div>
            </div>
          </div>
        );

      case 'BasicInfo':
        return (
          <div className="step-content basic-info">
            <h2 className="step-title">基本信息</h2>
            <p className="step-description">配置虚拟机的基本标识信息</p>

            <div className="form-grid">
              <div className="form-group">
                <label className="form-label required">虚拟机名称</label>
                <div className="input-wrapper">
                  <input
                    type="text"
                    className="form-input"
                    value={formData.name}
                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                    placeholder="my-virtual-machine"
                  />
                  {isCheckingName && <span className="input-status">检查中...</span>}
                </div>
                {nameAvailable === true && <span className="input-hint success">✓ 名称可用</span>}
                {nameAvailable === false && <span className="input-hint error">✗ 名称已被使用</span>}
                {errors.name && <span className="input-error">{errors.name}</span>}
              </div>

              <div className="form-group">
                <label className="form-label">描述</label>
                <textarea
                  className="form-textarea"
                  value={formData.description}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  placeholder="虚拟机描述（可选）"
                  rows={3}
                />
              </div>

              <div className="form-group">
                <label className="form-label required">操作系统类型</label>
                <select
                  className="form-select"
                  value={formData.osType}
                  onChange={(e) => setFormData({ ...formData, osType: e.target.value })}
                >
                  <option value="linux">Linux</option>
                  <option value="windows">Windows</option>
                  <option value="other">其他</option>
                </select>
                {errors.osType && <span className="input-error">{errors.osType}</span>}
              </div>

              <div className="form-group">
                <label className="form-label">操作系统版本</label>
                <select
                  className="form-select"
                  value={formData.osVersion}
                  onChange={(e) => setFormData({ ...formData, osVersion: e.target.value })}
                >
                  {formData.osType === 'linux' && (
                    <>
                      <option value="ubuntu22.04">Ubuntu 22.04</option>
                      <option value="ubuntu20.04">Ubuntu 20.04</option>
                      <option value="centos8">CentOS 8</option>
                      <option value="debian11">Debian 11</option>
                    </>
                  )}
                  {formData.osType === 'windows' && (
                    <>
                      <option value="win11">Windows 11</option>
                      <option value="win10">Windows 10</option>
                      <option value="win2019">Windows Server 2019</option>
                    </>
                  )}
                </select>
              </div>
            </div>
          </div>
        );

      case 'Resources':
        return (
          <div className="step-content resources">
            <h2 className="step-title">资源配置</h2>
            <p className="step-description">配置虚拟机的计算资源</p>

            {hostResources && (
              <div className="resource-summary">
                <div className="resource-item">
                  <span className="resource-label">可用CPU:</span>
                  <span className="resource-value">{hostResources.cpus} 核心</span>
                </div>
                <div className="resource-item">
                  <span className="resource-label">可用内存:</span>
                  <span className="resource-value">{(hostResources.memory.total / 1024 / 1024 / 1024).toFixed(1)} GB</span>
                </div>
              </div>
            )}

            <div className="form-grid">
              <div className="form-group">
                <label className="form-label required">CPU核心数</label>
                <div className="input-with-range">
                  <input
                    type="number"
                    className="form-input"
                    min="1"
                    max="128"
                    value={formData.vcpus}
                    onChange={(e) => setFormData({ ...formData, vcpus: parseInt(e.target.value) || 1 })}
                  />
                  <input
                    type="range"
                    className="form-range"
                    min="1"
                    max="32"
                    value={formData.vcpus}
                    onChange={(e) => setFormData({ ...formData, vcpus: parseInt(e.target.value) })}
                  />
                </div>
                {errors.vcpus && <span className="input-error">{errors.vcpus}</span>}
              </div>

              <div className="form-group">
                <label className="form-label required">内存大小</label>
                <div className="input-with-range">
                  <div className="memory-input">
                    <input
                      type="number"
                      className="form-input"
                      min="1"
                      max="256"
                      value={formData.memory}
                      onChange={(e) => setFormData({ ...formData, memory: parseInt(e.target.value) || 1 })}
                    />
                    <select
                      className="unit-select"
                      value={formData.memoryUnit}
                      onChange={(e) => setFormData({ ...formData, memoryUnit: e.target.value as 'MB' | 'GB' })}
                    >
                      <option value="GB">GB</option>
                      <option value="MB">MB</option>
                    </select>
                  </div>
                  <input
                    type="range"
                    className="form-range"
                    min="1"
                    max="64"
                    value={formData.memory}
                    onChange={(e) => setFormData({ ...formData, memory: parseInt(e.target.value) })}
                  />
                </div>
                {errors.memory && <span className="input-error">{errors.memory}</span>}
              </div>

              <div className="form-group">
                <label className="form-label">CPU模式</label>
                <select
                  className="form-select"
                  value={formData.cpuModel}
                  onChange={(e) => setFormData({ ...formData, cpuModel: e.target.value })}
                >
                  <option value="host-model">Host Model</option>
                  <option value="host-passthrough">Host Passthrough</option>
                  <option value="custom">自定义</option>
                </select>
              </div>
            </div>
          </div>
        );

      case 'ISOConfig':
        return (
          <div className="step-content iso-config">
            <h2 className="step-title">本地ISO配置</h2>
            <p className="step-description">配置本地ISO文件和CD-ROM设备</p>

            <div className="form-grid">
              <div className="form-group">
                <label className="form-label required">ISO文件路径</label>
                <div className="file-input-wrapper">
                  <input
                    type="text"
                    className="form-input"
                    value={formData.localIsoPath}
                    onChange={(e) => setFormData({ ...formData, localIsoPath: e.target.value })}
                    placeholder="/path/to/iso/file.iso"
                  />
                  <button className="file-browse-btn">浏览</button>
                </div>
                {errors.localIsoPath && <span className="input-error">{errors.localIsoPath}</span>}
              </div>

              <div className="form-group">
                <label className="form-checkbox">
                  <input
                    type="checkbox"
                    checked={formData.localIsoCdrom}
                    onChange={(e) => setFormData({ ...formData, localIsoCdrom: e.target.checked })}
                  />
                  <span className="checkmark"></span>
                  使用CD-ROM设备
                </label>
                <p className="input-hint">启用此选项将添加CD-ROM设备用于ISO引导</p>
              </div>
            </div>
          </div>
        );

      case 'NetworkInstall':
        return (
          <div className="step-content network-install">
            <h2 className="step-title">网络安装配置</h2>
            <p className="step-description">配置网络安装源和引导参数</p>

            <div className="form-grid">
              <div className="form-group">
                <label className="form-label required">安装源URL</label>
                <input
                  type="text"
                  className="form-input"
                  value={formData.networkSource}
                  onChange={(e) => setFormData({ ...formData, networkSource: e.target.value })}
                  placeholder="http://example.com/install/"
                />
                {errors.networkSource && <span className="input-error">{errors.networkSource}</span>}
              </div>

              <div className="form-group">
                <label className="form-label">内核路径</label>
                <input
                  type="text"
                  className="form-input"
                  value={formData.networkKernel}
                  onChange={(e) => setFormData({ ...formData, networkKernel: e.target.value })}
                  placeholder="/path/to/kernel"
                />
              </div>

              <div className="form-group">
                <label className="form-label">Initrd路径</label>
                <input
                  type="text"
                  className="form-input"
                  value={formData.networkInitrd}
                  onChange={(e) => setFormData({ ...formData, networkInitrd: e.target.value })}
                  placeholder="/path/to/initrd"
                />
              </div>

              <div className="form-group">
                <label className="form-label">额外内核参数</label>
                <input
                  type="text"
                  className="form-input"
                  value={formData.networkExtra}
                  onChange={(e) => setFormData({ ...formData, networkExtra: e.target.value })}
                  placeholder="console=ttyS0"
                />
              </div>
            </div>
          </div>
        );

      case 'DiskImport':
        return (
          <div className="step-content disk-import">
            <h2 className="step-title">磁盘导入配置</h2>
            <p className="step-description">选择要导入的磁盘映像文件</p>

            <div className="form-grid">
              <div className="form-group">
                <label className="form-label required">磁盘映像路径</label>
                <div className="file-input-wrapper">
                  <input
                    type="text"
                    className="form-input"
                    value={formData.importDiskPath}
                    onChange={(e) => setFormData({ ...formData, importDiskPath: e.target.value })}
                    placeholder="/path/to/disk.qcow2"
                  />
                  <button className="file-browse-btn">浏览</button>
                </div>
                {errors.importDiskPath && <span className="input-error">{errors.importDiskPath}</span>}
              </div>

              <div className="form-group">
                <label className="form-checkbox">
                  <input
                    type="checkbox"
                    checked={formData.importCopy}
                    onChange={(e) => setFormData({ ...formData, importCopy: e.target.checked })}
                  />
                  <span className="checkmark"></span>
                  复制磁盘文件
                </label>
                <p className="input-hint">启用此选项将在存储池中创建磁盘副本</p>
              </div>
            </div>
          </div>
        );

      case 'StorageConfig':
        return (
          <div className="step-content storage-config">
            <h2 className="step-title">存储配置</h2>
            <p className="step-description">配置虚拟机的存储设置</p>

            <div className="form-grid">
              <div className="form-group">
                <label className="form-label">存储池</label>
                <select
                  className="form-select"
                  value={formData.storagePool}
                  onChange={(e) => setFormData({ ...formData, storagePool: e.target.value })}
                >
                  {storagePools.map((pool: any) => (
                    <option key={pool.name} value={pool.name}>{pool.name}</option>
                  ))}
                </select>
              </div>

              <div className="form-group">
                <label className="form-label">磁盘大小 (GB)</label>
                <div className="input-with-range">
                  <input
                    type="number"
                    className="form-input"
                    min="1"
                    max="1000"
                    value={formData.diskSize}
                    onChange={(e) => setFormData({ ...formData, diskSize: parseInt(e.target.value) || 1 })}
                  />
                  <input
                    type="range"
                    className="form-range"
                    min="1"
                    max="200"
                    value={formData.diskSize}
                    onChange={(e) => setFormData({ ...formData, diskSize: parseInt(e.target.value) })}
                  />
                </div>
                {errors.diskSize && <span className="input-error">{errors.diskSize}</span>}
              </div>

              <div className="form-group">
                <label className="form-label">磁盘格式</label>
                <select
                  className="form-select"
                  value={formData.diskFormat}
                  onChange={(e) => setFormData({ ...formData, diskFormat: e.target.value })}
                >
                  <option value="qcow2">QCOW2 (推荐)</option>
                  <option value="raw">RAW</option>
                </select>
              </div>

              <div className="form-group">
                <label className="form-label">磁盘总线</label>
                <select
                  className="form-select"
                  value={formData.diskBus}
                  onChange={(e) => setFormData({ ...formData, diskBus: e.target.value })}
                >
                  <option value="virtio">VirtIO</option>
                  <option value="ide">IDE</option>
                  <option value="scsi">SCSI</option>
                </select>
              </div>

              <div className="form-group">
                <label className="form-label">缓存模式</label>
                <select
                  className="form-select"
                  value={formData.cacheMode}
                  onChange={(e) => setFormData({ ...formData, cacheMode: e.target.value })}
                >
                  <option value="writeback">Writeback</option>
                  <option value="writethrough">Writethrough</option>
                  <option value="none">None</option>
                </select>
              </div>
            </div>
          </div>
        );

      case 'NetworkConfig':
        return (
          <div className="step-content network-config">
            <h2 className="step-title">网络配置</h2>
            <p className="step-description">配置虚拟机的网络连接</p>

            <div className="form-grid">
              <div className="form-group">
                <label className="form-label">网络类型</label>
                <div className="radio-group">
                  <label className="radio-option">
                    <input
                      type="radio"
                      name="networkType"
                      value="nat"
                      checked={formData.networkType === 'nat'}
                      onChange={(e) => setFormData({ ...formData, networkType: e.target.value })}
                    />
                    <span className="radio-custom"></span>
                    <span className="radio-label">NAT</span>
                  </label>
                  <label className="radio-option">
                    <input
                      type="radio"
                      name="networkType"
                      value="bridge"
                      checked={formData.networkType === 'bridge'}
                      onChange={(e) => setFormData({ ...formData, networkType: e.target.value })}
                    />
                    <span className="radio-custom"></span>
                    <span className="radio-label">桥接</span>
                  </label>
                  <label className="radio-option">
                    <input
                      type="radio"
                      name="networkType"
                      value="user"
                      checked={formData.networkType === 'user'}
                      onChange={(e) => setFormData({ ...formData, networkType: e.target.value })}
                    />
                    <span className="radio-custom"></span>
                    <span className="radio-label">用户网络</span>
                  </label>
                </div>
              </div>

              {formData.networkType === 'nat' && (
                <div className="form-group">
                  <label className="form-label">虚拟网络</label>
                  <select
                    className="form-select"
                    value={formData.networkName}
                    onChange={(e) => setFormData({ ...formData, networkName: e.target.value })}
                  >
                    {networks.map((network: any) => (
                      <option key={network.name} value={network.name}>{network.name}</option>
                    ))}
                  </select>
                  {errors.networkName && <span className="input-error">{errors.networkName}</span>}
                </div>
              )}

              <div className="form-group">
                <label className="form-label">网络模型</label>
                <select
                  className="form-select"
                  value={formData.networkModel}
                  onChange={(e) => setFormData({ ...formData, networkModel: e.target.value })}
                >
                  <option value="virtio">VirtIO</option>
                  <option value="e1000">E1000</option>
                  <option value="rtl8139">RTL8139</option>
                </select>
              </div>

              <div className="form-group">
                <label className="form-label">MAC地址</label>
                <div className="mac-input-wrapper">
                  <input
                    type="text"
                    className="form-input"
                    value={formData.macAddress}
                    onChange={(e) => setFormData({ ...formData, macAddress: e.target.value })}
                    placeholder="52:54:00:XX:XX:XX"
                  />
                  <button className="generate-btn" onClick={generateMACAddress}>生成</button>
                </div>
                {errors.macAddress && <span className="input-error">{errors.macAddress}</span>}
              </div>
            </div>
          </div>
        );

      case 'BootOptions':
        return (
          <div className="step-content boot-options">
            <h2 className="step-title">启动选项</h2>
            <p className="step-description">配置虚拟机的启动行为</p>

            <div className="form-grid">
              <div className="form-group">
                <label className="form-label">启动顺序</label>
                <div className="boot-order-list">
                  {['cdrom', 'hd', 'network'].map((device) => (
                    <div key={device} className="boot-order-item">
                      <label className="form-checkbox">
                        <input
                          type="checkbox"
                          checked={formData.bootOrder.includes(device)}
                          onChange={(e) => {
                            const newOrder = e.target.checked
                              ? [...formData.bootOrder, device]
                              : formData.bootOrder.filter(item => item !== device);
                            setFormData({ ...formData, bootOrder: newOrder });
                          }}
                        />
                        <span className="checkmark"></span>
                        {device === 'cdrom' && 'CD-ROM'}
                        {device === 'hd' && '硬盘'}
                        {device === 'network' && '网络'}
                      </label>
                    </div>
                  ))}
                </div>
              </div>

              <div className="form-group">
                <label className="form-checkbox">
                  <input
                    type="checkbox"
                    checked={formData.autostart}
                    onChange={(e) => setFormData({ ...formData, autostart: e.target.checked })}
                  />
                  <span className="checkmark"></span>
                  自动启动
                </label>
                <p className="input-hint">宿主机启动时自动启动此虚拟机</p>
              </div>

              <div className="form-group">
                <label className="form-label">启动延迟 (秒)</label>
                <input
                  type="number"
                  className="form-input"
                  min="0"
                  max="60"
                  value={formData.bootDelay}
                  onChange={(e) => setFormData({ ...formData, bootDelay: parseInt(e.target.value) || 0 })}
                />
                <p className="input-hint">虚拟机启动前的延迟时间</p>
              </div>

              <div className="form-group">
                <label className="form-label">引导加载器</label>
                <div className="radio-group">
                  <label className="radio-option">
                    <input
                      type="radio"
                      name="loader"
                      value="uefi"
                      checked={formData.loader === 'uefi'}
                      onChange={(e) => setFormData({ ...formData, loader: e.target.value })}
                    />
                    <span className="radio-custom"></span>
                    <span className="radio-label">UEFI</span>
                  </label>
                  <label className="radio-option">
                    <input
                      type="radio"
                      name="loader"
                      value="bios"
                      checked={formData.loader === 'bios'}
                      onChange={(e) => setFormData({ ...formData, loader: e.target.value })}
                    />
                    <span className="radio-custom"></span>
                    <span className="radio-label">BIOS</span>
                  </label>
                </div>
              </div>

              <div className="form-group">
                <label className="form-label">图形设备</label>
                <select
                  className="form-select"
                  value={formData.graphics}
                  onChange={(e) => setFormData({ ...formData, graphics: e.target.value })}
                >
                  <option value="vnc">VNC</option>
                  <option value="spice">SPICE</option>
                </select>
              </div>
            </div>
          </div>
        );

      case 'XMLConfig':
        return (
          <div className="step-content xml-config">
            <h2 className="step-title">XML配置</h2>
            <p className="step-description">输入自定义的虚拟机XML配置</p>

            <div className="form-group">
              <label className="form-label required">XML配置</label>
              <textarea
                className="form-textarea xml-editor"
                value={formData.customXml}
                onChange={(e) => setFormData({ ...formData, customXml: e.target.value })}
                placeholder="&lt;domain type='kvm'&gt;...&lt;/domain&gt;"
                rows={20}
                spellCheck={false}
              />
              {errors.customXml && <span className="input-error">{errors.customXml}</span>}
              <p className="input-hint">输入符合libvirt规范的XML配置</p>
            </div>
          </div>
        );

      default:
        return null;
    }
  };

  if (!isOpen) return null;

  return (
    <div className="podman-wizard-overlay">
      <div className="podman-wizard-container">
        <div className="wizard-header">
          <div className="wizard-title-section">
            <h1 className="wizard-title">创建虚拟机</h1>
            <p className="wizard-subtitle">配置新的虚拟机实例</p>
            {autoSaveStatus !== 'idle' && (
              <div className="auto-save-status">
                {autoSaveStatus === 'saving' && (
                  <>
                    <span className="spinner small"></span>
                    自动保存中...
                  </>
                )}
                {autoSaveStatus === 'saved' && (
                  <>
                    <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor">
                      <path d="M10 3L4.5 8.5L2 6" stroke="currentColor" strokeWidth="2" fill="none"/>
                    </svg>
                    已自动保存
                  </>
                )}
              </div>
            )}
          </div>
          <button className="wizard-close-btn" onClick={onClose}>
            <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
              <path d="M8 8l3.535 3.535-1.415 1.415L8 9.415 4.465 12.95 3.05 11.535 6.585 8 3.05 4.465 4.465 3.05 8 6.585 11.535 3.05l1.415 1.415L9.415 8z"/>
            </svg>
          </button>
        </div>

        <div className="wizard-body">
          {/* 步骤指示器 */}
          <div className="wizard-progress">
            <div className="progress-bar">
              <div
                className="progress-fill"
                style={{ width: `${((currentStep - 1) / (steps.length - 1)) * 100}%` }}
              />
            </div>
            <div className="step-indicators">
              {steps.map((step, index) => (
                <div
                  key={step.id}
                  className={`step-indicator ${index + 1 <= currentStep ? 'completed' : ''} ${index + 1 === currentStep ? 'active' : ''}`}
                >
                  <div className="step-number">{index + 1}</div>
                  <div className="step-title">{step.title}</div>
                </div>
              ))}
            </div>
          </div>

          {/* 步骤内容 */}
          <div className="wizard-content">
            {renderStepContent()}
          </div>

          {/* 错误信息 */}
          {errors.submit && (
            <div className="wizard-error">
              <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
                <path d="M8 0a8 8 0 100 16A8 8 0 008 0zM7 11V6h2v5H7zm0-6V3h2v2H7z"/>
              </svg>
              {errors.submit}
            </div>
          )}
        </div>

        <div className="wizard-footer">
          <div className="wizard-actions">
            <button
              className="btn btn-secondary"
              onClick={onClose}
              disabled={isSubmitting}
            >
              取消
            </button>

            <div className="wizard-nav">
              <button
                className="btn btn-secondary"
                onClick={handlePrevious}
                disabled={currentStep === 1 || isSubmitting}
              >
                上一步
              </button>

              <button
                className="btn btn-primary"
                onClick={handleNext}
                disabled={isSubmitting}
              >
                {isSubmitting ? (
                  <>
                    <span className="spinner"></span>
                    创建中...
                  </>
                ) : (
                  currentStep === steps.length ? '创建虚拟机' : '下一步'
                )}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default CreateVMWizardPodman;